// src/store/modules/websocket.js
import Vue from 'vue'

const state = {
  socket: null,
  messages: []
}

const mutations = {
  SET_SOCKET(state, socket) {
    state.socket = socket
  },
  ADD_MESSAGE(state, message) {
    state.messages.push(message)
  }
}

const actions = {
  initWebSocket({ commit }, username) {
    console.log('initWebSocket')
    const socketUrl = `ws://localhost:1003/monitor/socket?erp=${encodeURIComponent(username)}`
    const socket = new WebSocket(socketUrl)

    socket.onopen = () => {
      console.log('WebSocket连接已打开')
      commit('SET_SOCKET', socket)
    }

    socket.onmessage = (event) => {
      console.log('收到消息:', event.data)
      commit('ADD_MESSAGE', event.data)
      // 使用Element UI的Message组件显示消息
      Vue.prototype.$message({
        message: event.data,
        type: 'warning'
      })
    }

    socket.onerror = (error) => {
      console.error('WebSocket错误:', error)
      Vue.prototype.$message({
        message: 'WebSocket连接错误',
        type: 'error'
      })
    }

    socket.onclose = () => {
      console.log('WebSocket连接已关闭')
      commit('SET_SOCKET', null)
    }
  }
}

const getters = {
  socket: state => state.socket,
  messages: state => state.messages
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}